package com.compass.mobile.ui.fragment

import UserInfoManager
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentMyAppointmentBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.Appointment
import com.compass.mobile.presenters.AppointmentPresenter
import com.compass.mobile.ui.activity.DoctorRegisterHomeActivity
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.viewModel.AppointmentViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import getStringFromResource

/**
 * Description： 我的预约
 * Date:2024/5/22 13:39
 */
class MyAppointmentFragment : BaseVBFragment<FragmentMyAppointmentBinding>() {

    private val appointmentViewModel: AppointmentViewModel by viewModels()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var orders: MutableList<Appointment> = mutableListOf()
    private var mPage = 1
    private var isHaveNext = true
    private var type: String = "1"

    override fun initView(view: View, savedInstanceState: Bundle?) {
        specialColumn()
    }

    fun setSelect(type: String) {
        showLoading()
        this.type = type
        mPage = 1
        arrayObjectAdapter.clear()
        appointmentViewModel.getAppointmentList(UserInfoManager.getPatientInfo()?.id, type, mPage)
    }

    override fun initData() {
        appointmentViewModel.appointmentOrdersLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    arrayObjectAdapter.clear()
                    mBinding?.emptyView?.visible()
                    mBinding?.llBelow?.gone()
                } else {
                    isHaveNext(it.size)
                    mBinding?.emptyView?.gone()
                    orders = it
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, orders)
                }
            } else {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    mPage-- //恢复上一次的page
                    showToast("没有下一页了")
                } else {
                    isHaveNext(it.size)
                    orders = it
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, orders)
                }
            }
        }
        appointmentViewModel.cancelAppointmentLiveData.observe(this) {
            dismissLoading()
            it?.let {
                showToast("取消成功！")
                appointmentViewModel.getAppointmentList(
                    UserInfoManager.getPatientInfo()?.id,
                    type,
                    mPage
                )
            }
        }
    }


    private fun isHaveNext(number: Int) {
        if (number < 10) {
            isHaveNext = false
        } else {
            mBinding?.llBelow?.visible()
            isHaveNext = true
        }
    }

    override fun intListener() {
        mBinding?.tvPrevious?.onClick {
            if (mPage > 1) {
                mPage--
                appointmentViewModel.getAppointmentList(
                    UserInfoManager.getPatientInfo()?.id,
                    type,
                    mPage
                )
            } else {
                showToast("没有上一页了")
            }
        }

        mBinding?.tvNextPage?.onClick {
            if (isHaveNext) {
                mPage++
                appointmentViewModel.getAppointmentList(
                    UserInfoManager.getPatientInfo()?.id,
                    type,
                    mPage
                )
            } else {
                showToast("没有下一页了")
            }
        }
    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {

            val appointmentOrder = orders[position]
            when (appointmentOrder.euStatus) {
                "0" -> {
                    //取消预约
                    cancelInquire(appointmentOrder.pkSchappt)
                }

                else -> {
                    //再次预约
                    if (appointmentOrder.doctorId.isNullOrEmpty()||appointmentOrder.departmentId.isNullOrEmpty()){
                        showToast("该医生暂不支持再次预约")
                    }else{
                        DoctorRegisterHomeActivity.start(
                            requireContext(),
                            appointmentOrder.doctorId,
                            appointmentOrder.departmentId
                        )
                    }


                }
            }


        }
    }


    /**
     * 取消预约
     */
    private fun cancelInquire(pkSchappt: String) {
        CommonMessageDialog.Builder(requireActivity())
            .setTitle("温馨提示")
            .setMessage("确认要取消当前预约吗?")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                it?.dismiss()
                showLoading()
                appointmentViewModel.cancelAppointment(pkSchappt)

            }.create().show()


    }


    @SuppressLint("RestrictedApi")
    fun specialColumn() {

        mBinding?.caseItem?.horizontalSpacing = dpToPx(10)
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)
        arrayObjectAdapter = ArrayObjectAdapter(AppointmentPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )
        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        mBinding?.caseItem?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, orders)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )

    }

}